package com.slh.touchandroid.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.IntentCompat;
import android.view.MenuItem;

import com.slh.touchandroid.R;
import com.slh.touchandroid.fragment.BrightnessFragment;
import com.slh.touchandroid.fragment.BrowserFragment;
import com.slh.touchandroid.fragment.InstalledAppFragment;
import com.slh.touchandroid.fragment.LightFragment;
import com.slh.touchandroid.fragment.MirrorFragment;
import com.slh.touchandroid.fragment.PickAppFragment;
import com.slh.touchandroid.fragment.RunningAppsFragment;
import com.slh.touchandroid.fragment.TouchFragment;
import com.slh.touchandroid.service.TouchService;
import com.slh.touchandroid.utils.AppUtils;
import com.slh.touchandroid.utils.CONFIG;
import com.slh.touchandroid.utils.Logging;
import com.slh.touchandroid.utils.Utils;

public class TouchActivity extends BaseActivity {
	// ====================================================================================
	public static final String ACTION_LIGHT = "com.slh.touchandroid.activity.ACTION_LIGHT";
	public static final String ACTION_MIRROR = "com.slh.touchandroid.activity.ACTION_MIRROR";
	public static final String ACTION_INSTALLED_APP = "com.slh.touchandroid.activity.ACTION_INSTALLED_APP";
	public static final String ACTION_RUNNING_APP = "com.slh.touchandroid.activity.ACTION_RUNNING_APP";
	public static final String ACTION_MAIN = "com.slh.touchandroid.activity.ACTION_MAIN";
	public static final String ACTION_BRIGHTNESS = "com.slh.touchandroid.activity.ACTION_BRIGHTNESS";
	public static final String ACTION_FILE_BROWSER = "com.slh.touchandroid.activity.ACTION_FILE_BROWSER";
	public static final String ACTION_FINISH = "com.slh.touchandroid.activity.ACTION_FINISH";
	public static final String ACTION_SETTINGS = "com.slh.touchandroid.activity.ACTION_SETTINGS";
	public static final String ACTION_PICK_APP = "com.slh.touchandroid.activity.ACTION_PICK_APP";

	public static final String EXTRA_PICK_APP_POSITION = "EXTRA_PICK_APP_POSITION";

	// ====================================================================================
	public static void start(Context context) {
		Intent intent = new Intent(context, TouchActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
		context.startActivity(intent);
	}

	public static void start(Context context, String action) {
		Intent intent = new Intent(context, TouchActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
		intent.setAction(action);
		context.startActivity(intent);
	}

	public static void start(Context context, String action, Bundle bundle) {
		Intent intent = new Intent(context, TouchActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
		intent.setAction(action);
		intent.putExtras(bundle);
		context.startActivity(intent);
	}

	// ====================================================================================
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		TouchService.startAndroidTouch(getApplicationContext());
		String action = getIntent().getAction();
		if (ACTION_LIGHT.equals(action)) {
			findFragment(new LightFragment(), action);
		} else if (ACTION_MIRROR.equals(action)) {
			findFragment(new MirrorFragment(), action);
		} else if (ACTION_INSTALLED_APP.equals(action)) {
			findFragment(new InstalledAppFragment(), action);
		} else if (ACTION_BRIGHTNESS.equals(action)) {
			findFragment(new BrightnessFragment(), action);
		} else if (ACTION_FILE_BROWSER.equals(action)) {
			findFragment(
					BrowserFragment.newInstance(BrowserFragment.ROOT_FILE),
					action);
		} else if (ACTION_FINISH.equals(action)) {
			finish();
		} else if (ACTION_PICK_APP.equals(action)) {
			findFragment(PickAppFragment.newInstance(getIntent().getExtras()),
					action);
		} else if (ACTION_SETTINGS.equals(action)) {
			findFragment(PickAppFragment.newInstance(getIntent().getExtras()),
					action);
		} else if (ACTION_RUNNING_APP.equals(action)) {
			findFragment(new RunningAppsFragment(), action);
		} else {
			findFragment(new TouchFragment(), action);
		}
		setContentView(R.layout.activity_touch);
		// Logging.log(getInfo());
		// SimInfo info = SIMUtils.getSIM2(this);
		// Logging.log("deviceId",info.deviceId);
		// Properties properties = System.getProperties();
		// Enumeration<Object> keys = properties.keys();
		// while (keys.hasMoreElements()) {
		// String object = (String) keys.nextElement();
		// Logging.log(object, properties.get(object));
		// }

		// SettingsUtils.getAllSensors(this);

		// Logging.log(Build.getRadioVersion());

		Logging.log(System.getProperties().get("ro.media.enc.vid.codec"));
	}

	private String getInfo() {
		StringBuffer sb = new StringBuffer();
		sb.append("abi: ").append(Build.CPU_ABI).append("\n");
		sb.append("abi2: ").append(Build.CPU_ABI2).append("\n");
		if (new File("/proc/cpuinfo").exists()) {
			try {
				BufferedReader br = new BufferedReader(new FileReader(new File(
						"/proc/cpuinfo")));
				String aLine;
				while ((aLine = br.readLine()) != null) {
					sb.append(aLine + "\n");
				}
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case android.R.id.home:
			if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
				onBackPressed();
			}
			break;
		case R.id.action_feedback:
			AppUtils.sendEmail(TouchActivity.this, CONFIG.FEEDBACK.EMAIL,
					CONFIG.FEEDBACK.SUBJECT, "");
			break;
		case R.id.action_uninstall:
			CONFIG.ADMIN_DEVICE.removeDeviceAdmin(getApplicationContext());
			AppUtils.uninstallApp(getApplicationContext(), getPackageName());
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// ====================================================================================
	private void findFragment(Fragment fragment, String tag) {
		FragmentManager fragmentManager = getSupportFragmentManager();
		Fragment found = fragmentManager.findFragmentByTag(tag);
		if (found == null) {
			fragmentManager.beginTransaction()
					.add(R.id.container, fragment, tag).commit();
		}
	}

	// =======================================================================================
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
	}
}
